<?php
class Router {
	
	public $application_dir = 'application';
	public $routes =	array();
	public $action = '';
	public $method = '';
	
	public function __construct()
	{
		global $sysdata;
		if($sysdata['application_dir']&&is_dir(APPPATH.$sysdata['application_dir'])) $this->application_dir = $sysdata['application_dir'];
		if(is_file(APPDATA.'cnf/routes.php')){
			$this->routes = include APPDATA.'cnf/routes.php';
		}
	}
	public function set_routes(){
		global $application;
		$url = $this->get_url();
		if(is_array($this->routes)){
			foreach ($this->routes as $k => $v)
			{
				if (preg_match('#^'.$k.'$#', $url, $matches))
				{
					if (strpos($v, '$') !== FALSE && strpos($k, '(') !== FALSE)
					{
						$url = preg_replace('#^'.$k.'$#', $v, $url);
					}else{
						$url = $v;
					}
				}
			}
		}
		if($url){
			$urlArr = explode("/",$url);
			$urlArr = array_filter($urlArr);
			$this->action = $urlArr[0];
			$this->method = $urlArr[1];
			for($i=2;$i<count($urlArr);$i+=2){
				$_GET[$urlArr[$i]] = $urlArr[($i+1)];
			}
		}
		if($this->action){
			$path = APPPATH.$this->application_dir.'/'.$this->action.'.php';
			if(!is_file($path)){
				$this->action = '';
				$_GET["act"] = 'show_404';
			}else{
				$_GET["action"] = $this->action;
				if($this->method) $_GET["act"] = $this->method;
				require $path;
			}
		}else{
			
		}
	}
	private function get_url(){
		$Rurl = str_replace('index.php','',$_SERVER['REQUEST_URI']);
		if(APPURL!='/') $Rurl = str_replace(APPURL,'',$Rurl);
		return preg_replace('/\/{1,}/','/',trim(trim($Rurl),'/'));
	}
}

?>